package com.zxt.dao.impl;

import com.zxt.dao.UserDao;
import com.zxt.domain.User;
import com.zxt.util.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
  private QueryRunner queryRunner=new QueryRunner(DataSourceUtils.getDataSource());
    @Override
    public User selectByUsername(String username) {
        try {
            return queryRunner.query("select * from tb_user where username=?",new BeanHandler<>(User.class),username);
        } catch (SQLException e) {
           throw new RuntimeException(e);
        }
    }

    @Override
    public void insert(User user) {
        String sql="insert into tb_user values (null,?,?,?,?,?,?,?)";
        Object [] params={user.getUsername(),user.getPassword(),user.getEmail(),
        user.getGender(),user.getFlag(),user.getRole(),user.getCode()};
        try {
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int updateFlag(String email, String code) {
        String sql="update tb_user set flag=1 where email=? and code=? and flag=0";
        try {
            return queryRunner.update(sql,email,code);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
